<template>
  <div class="content">
    <el-card style="margin-bottom: 20px">
      <div style="display: flex; align-items: center; justify-content: space-between">
        <el-button type="primary" @click="addUserInfo">添加</el-button>
        <div>
          用户名：
          <el-input v-model="params.username" style="width: 240px; margin-right: 20px" placeholder="请输入用户名" />
          手机号：
          <el-input v-model="params.phone" style="width: 240px; margin-right: 20px" placeholder="请输入手机号" />
          <el-button @click="getNewUserInfo" type="primary">搜索</el-button>
          <el-button @click="clickReset">重置</el-button>
        </div>
      </div>
    </el-card>
    <el-card>
      <!-- 底部table列表 -->
      <el-table :data="tableData" style="width: 100%">
        <el-table-column show-overflow-tooltip prop="userId" label="用户ID" />
        <el-table-column show-overflow-tooltip prop="nickName" label="昵称" />
        <el-table-column show-overflow-tooltip prop="username" label="账号" />
        <el-table-column show-overflow-tooltip prop="email" label="邮箱" />
        <el-table-column show-overflow-tooltip prop="phone" label="手机号" />
        <el-table-column show-overflow-tooltip prop="roleName" label="角色名称" />
        <el-table-column show-overflow-tooltip prop="roleId" label="绑定角色ID" />
        <el-table-column label="操作" width="240">
          <template #default="scope">
            <el-button size="small" @click="clickViewUserInfo(scope.row)" :icon="View">查看</el-button>
            <el-button size="small" @click="clickEditUserInfo(scope.row)" :icon="EditPen" type="primary">编辑</el-button>
            <el-popconfirm
              class="box-item"
              title="删除后将无法回复，是否删除"
              placement="top-end"
              @confirm="delUserInfo(scope.row)"
            >
              <template #reference><el-button size="small" :icon="Delete" type="danger">删除</el-button> </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="page-content" v-if="total / params.pageSize > 1">
        <el-pagination
          background
          :total="total"
          layout="prev, pager, next"
          :page-size="params.pageSize"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 添加 / 编辑 -->
    <el-dialog v-model="userDrawerShow" :title="userType == 0 ? '添加人员' : userType == 1 ? '查看人员' : '编辑人员'" width="500">
      <el-form :model="userInfo" label-width="auto" :rules="rules" ref="userForm">
        <el-form-item label="昵称：" prop="nickName">
          <el-input placeholder="请输入昵称" v-model="userInfo.nickName" :disabled="userType == 1" />
        </el-form-item>
        <el-form-item label="账号：" prop="username">
          <el-input placeholder="请输入账号" v-model="userInfo.username" :disabled="userType == 1" />
        </el-form-item>
        <el-form-item label="手机号：" prop="phone">
          <el-input placeholder="请输入手机号" v-model="userInfo.phone" :disabled="userType == 1" />
        </el-form-item>
        <el-form-item label="邮箱：" prop="email">
          <el-input placeholder="请输入邮箱" v-model="userInfo.email" :disabled="userType == 1" />
        </el-form-item>
        <el-form-item label="密码：" prop="password">
          <el-input placeholder="请输入密码" type="password" v-model="userInfo.password" :disabled="userType == 1" />
        </el-form-item>
        <el-form-item label="角色：">
          <el-select v-model="userInfo.roleId" placeholder="请选择角色身份" :disabled="userType == 1">
            <el-option :label="item.roleName" :value="item.roleId" v-for="(item, idx) in sysRoleList" :key="idx" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="userType !== 1">
          <el-button @click="clickAddForm" style="flex: 1" type="primary">保存</el-button>
          <el-button @click="clickFormReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup lang="js" name="userInfo">
import { ref } from "vue";
import { Delete, EditPen, View } from "@element-plus/icons-vue";
import {
  getNewUserTreeList,
  getNewAddUserTree,
  getNewEditUserTreeList,
  getNewDelUserTreeList,
  getNewSysRoleTreeList
} from "@/api/modules/user";

const total = ref(0); // 总条数
const userType = ref(0);
const userForm = ref(null);
const tableData = ref([]); // 表格数据
const userDrawerShow = ref(false); // 抽屉显示隐藏

const userInfo = ref({
  userId: "", // 用户ID
  username: "", // 账号（唯一）
  password: "", // 密码（明文）
  nickName: "", // 昵称
  email: "", // 邮箱
  phone: "", // 手机号（格式校验）
  roleId: "" // 绑定角色ID（可选）
});
const rules = ref({
  nickName: [{ required: true, message: "请输入昵称", trigger: "blur" }],
  username: [
    { required: true, message: "请输入账号", trigger: "blur" },
    { min: 3, max: 20, message: "账号长度需在3-20字符之间", trigger: "blur" }
  ],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "手机号格式不正确（11位数字）", trigger: "blur" }
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "邮箱格式不正确", trigger: "blur" }
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 20, message: "密码长度需在6-20字符之间", trigger: "blur" }
  ],
  roleId: [{ required: true, message: "请输入角色ID", trigger: "blur" }]
});

// 查看
const clickViewUserInfo = row => {
  userInfo.value = row;
  userType.value = 1;
  userDrawerShow.value = true;
};

// 角色身份
const sysRoleList = ref([]);
const getSysRoleList = async () => {
  const res = await getNewSysRoleTreeList();
  if (res.code == 200) {
    sysRoleList.value = res.data;
    console.log(sysRoleList.value);
  }
};
getSysRoleList();

// 编辑
const clickEditUserInfo = row => {
  userInfo.value = row;
  userType.value = 2;
  userDrawerShow.value = true;
};

// 删除
const delUserInfo = async row => {
  const res = await getNewDelUserTreeList({ userId: row.userId });
  if (res.code == 200) {
    getNewUserInfo();
  }
};

const params = ref({
  pageSize: 10,
  pageNo: 1,
  username: "",
  phone: ""
});

// 添加页码变化处理函数
const handleCurrentChange = currentPage => {
  // 更新当前页码参数
  params.value.pageNo = currentPage;
  // 重新加载数据
  getNewUserInfo();
};

// 重置
const clickReset = () => {
  params.value.phone = "";
  params.value.username = "";
};

// 重置表单
const clickFormReset = () => {
  userInfo.value = {
    username: "", // 账号（唯一）
    password: "", // 密码（明文）
    nickName: "", // 昵称
    email: "", // 邮箱
    phone: "", // 手机号（格式校验）
    roleId: "" // 绑定角色ID（可选）
  };
};

// 添加表单
const clickAddForm = async () => {
  const isValid = await new Promise(resolve => {
    userForm.value?.validate(valid => {
      resolve(valid);
    });
  });

  if (!isValid) return;

  if (userType.value == 0) {
    const res = await getNewAddUserTree(userInfo.value);
    if (res.code == 200) {
      userDrawerShow.value = false;
      getNewUserInfo();
    }
    return;
  }
  const resEdit = await getNewEditUserTreeList(userInfo.value);
  if (resEdit.code == 200) {
    userDrawerShow.value = false;
    getNewUserInfo();
  }
};

// 获取用户列表
const getNewUserInfo = async () => {
  const res = await getNewUserTreeList(params.value);
  total.value = res.data.total;
  tableData.value = res.data.records;
};
getNewUserInfo();

// 添加用户
const addUserInfo = () => {
  userType.value = 0;
  userDrawerShow.value = true;
  userInfo.value.userId = "";
};
</script>
<style lang="scss" scoped>
.page-content {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
